import java.util.Arrays;

public class MyArrayList<E> {
    private Object [] myArrayList = new Object[10];
    private int size;
    private int defaultLength = 10;


    @Override
    public String toString() {
        Object[] myPrint = new Object[size];
        for (int i = 0; i < size; i++) {
            myPrint[i] = myArrayList[i];
        }
        return  Arrays.toString(myPrint);
    }

    //开发 add 方法
    public boolean add(E e){
        //先检查
        if (!check()) {
            //扩容，每一次扩容都是1.5倍
            defaultLength = (int) (defaultLength * 1.5);
            //再创建新的数组
            Object[] newlyArray = new Object[defaultLength];
            for (int i = 0; i < size; i++) {
                newlyArray[i] = myArrayList[i];
            }
            myArrayList = newlyArray;
        }
        myArrayList[size++] = e;
        return true;
    }
    // 开发一个 forEach 方法
    public void forEach(Consumer<E> consumer){
        if (consumer == null){
            throw new RuntimeException(" consumer == null！！！");
        }
        for (int i = 0; i < size; i++) {
            consumer.accept((E)myArrayList[i]);
        }
    }

    //开发根据索引查询数据的 get() 方法
    public E get(int index){
        if (index >= size || index < 0){
            throw new RuntimeException("越界行为");
        }else {
            return (E)myArrayList[index];
        }
    }

    //开发根据索引删除数据 remove 方法
    public boolean remove(int index){
        if (index >= size || index < 0){
            throw new RuntimeException("越界行为");
        }else {
            removeFun(index);
            size--;
            return true;
        }
    }
    //开发一个获取集合大小的 size 方法
    public int size(){
        return size;
    }
    //遍历删除
    //[1,2,3,4,5,6]
    // 0 1 2 3 4 5
    private void removeFun(int index){
        int interval = size-index - 1;
        if (interval == 0){
            //只需要删除最后一个元素,覆盖就好了。
        } else if (interval > 0) {
            // 3      3 + 6 - 3 - 1
            // 3         5
            for (int i = index; i < index + interval; i++) {
                myArrayList[i] = myArrayList[i+1];
            }
        }else {
            throw new RuntimeException("越界了");
        }
    }


    //检查是否越界
    private boolean check(){
        if (size >= defaultLength ||size < 0){
            return false;
        }else {
            return true;
        }
    }

    public MyArrayList() {
    }

    public MyArrayList(Object[] myArrayList) {
        this.myArrayList = myArrayList;
    }

}
